<?php
/**
 * Created by PhpStorm.
 * User: lullabies
 * Date: 2019/5/27
 * Time: 10:33
 */

namespace app\admin\controller;
use app\admin\model\Exam as ExamModel;
use app\Admin\model\Grade;
use app\admin\model\TotalGrade;
use app\Admin\validate\AddSubjects;
use app\Admin\validate\UpdateSubjects;
use app\Admin\validate\ExamValidate;
use app\api\validate\IDMustBePositiveInt;
use app\Admin\model\Subjects as SubjectsModel;
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,fs-token");
header('Access-Control-Allow-Methods: GET, POST');
/**
 * @title 考试管理
 * @group Admin
 */
class Exam extends Base
{
    /**
     * @title 考试列表
     * @author 开发者
     * @url /admin/exam/listExam
     * @method POST/GET
     * @description  默认获取所有类型的考试 根据tab值可选择联考还是校考
     * @param name:tab require:0 default:null type:int desc:默认null，可自行设置1联考2校考
     * @param name:region require:0 default:null type:varchar desc:默认显示全国信息，可自行选择
     * @param name:page require:0 default:1 type:int desc:当前页面数  默认第一页
     * @param name:page_size require:0 default:10 type:int desc:每页显示记录数 默认10条
     * @param name:sort require:0 default:update_time type:vatchar desc:排序关键字 默认更新时间
     * @param name:order require:0 default:desc type:varchar desc:默认排序为降序
     * @return  id:考试id
     * @return  title:考试标题
     * @return intro:考试说明
     * @return exam_time:考试时间
     * @return region:地区
     * @return school:学校
     * @return tab:1联考 2 校考
     * @return create_time: 创建时间
     * @return update_time:更新时间
     * @return subjects:科目@
     * @subjects subject_id:科目id name:科目名称 price:科目价格
     * @return total_page:总页数
     */
    public function listExam(){
       //获取考试类型
        $tab = input('tab');
        $con=array();
        if($tab){
            $con['tab'] = $tab;
        }
        //地区获取
        $region = input('region');
        if($region){
            $con['region'] = $region;
        }
        //获得前端显示的当前页数
        $page = input('page', 1, 'intval');
        //让前端设置数据一页显示几条数据
        $page_size = input('page_size', 10, 'intval');
        //排序的关键字
        $sort = input('sort','update_time');
        //显示顺序
        $order = input('order','desc');
        if(!$tab){
            if(!$region){
                $result = ExamModel::where('status',1)
                    ->page($page,$page_size)
                    ->order($sort,$order)
                    ->select();
                $count = ExamModel::total();
            }else{
                $result = ExamModel::where(['status'=>1,'region'=>$region])
                    ->page($page,$page_size)
                    ->order($sort,$order)
                    ->select();
                $count = ExamModel::total($con);
            }
        }else{
            if(!$region){
                $result = ExamModel::where(['tab'=>$tab,'status'=>1])
                    ->page($page,$page_size)
                    ->order($sort,$order)
                    ->select();
            }else{
                $result = ExamModel::where(['tab'=>$tab,'status'=>1,'region'=>$region])
                    ->page($page,$page_size)
                    ->order($sort,$order)
                    ->select();
            }
            $count = ExamModel::total($con);
        }
        if($result->isEmpty()){
            $this->apiReturn(303,'未查询到数据!');
        }else{
            foreach($result as $k=>$v){
                //根据考试id进行科目关联查询
                $subject[]= ExamModel::with(['subjects'=>function($query){
                    $query->field(['id as subject_id','exam_id','name','price'])->where('status',1);
                }])->find($v['id']);
            }
            $this->apiReturn(200,'查询成功',$subject,$count);
        }
    }
    /**
     * @title 假删除数据的考试列表
     * @author 开发者
     * @url /admin/exam/listDelExam
     * @method POST/GET
     * @description  默认获取所有假删除的考试列表 根据tab值可选择联考还是校考
     * @param name:tab require:0 default:null type:int desc:默认null，可自行设置1联考2校考
     * @param name:page require:0 default:1 type:int desc:当前页面数  默认第一页
     * @param name:page_size require:0 default:10 type:int desc:每页显示记录数 默认10条
     * @param name:sort require:0 default:update_time type:vatchar desc:排序关键字 默认更新时间
     * @param name:order require:0 default:desc type:varchar desc:默认排序为降序
     * @return  id:考试id
     * @return  title:考试标题
     * @return intro:考试说明
     * @return exam_time:考试时间
     * @return region:地区
     * @return school:学校
     * @return tab:1联考 2 校考
     * @return create_time: 创建时间
     * @return update_time:更新时间
     * @return subjects:科目@
     * @subjects subject_id:科目id name:科目名称 price:科目价格
     * @return total_page:总页数
     */
    public function listDelExam(){
        $tab = [
            'tab' => input('tab')
        ];
        //获得前端显示的当前页数
        $page = input('page', 1, 'intval');
        //让前端设置数据一页显示几条数据
        $page_size = input('page_size', 10, 'intval');
        //排序的关键字
        $sort = input('sort','update_time');
        //显示顺序
        $order = input('order','desc');
        if(!$tab['tab']){
            $result = ExamModel::where('status',2)
                ->page($page,$page_size)
                ->order($sort,$order)
                ->select();
            $count = ExamModel::total();
        }else{
            $result = ExamModel::where(['tab'=>$tab,'status'=>2])
                ->page($page,$page_size)
                ->order($sort,$order)
                ->select();
            $count = ExamModel::total($tab);
        }
        if($result->isEmpty()){
            $this->apiReturn(303,'未查询到数据!');
        }else{
            //将对象转换为数组
            $result->toArray();
            foreach($result as $k=>$v){
                //根据考试id进行科目关联查询
                $subject[]= ExamModel::with(['subjects'=>function($query){
                    $query->field(['id as subject_id','exam_id','name','price'])->where('status',2);
                }])->find($v['id']);
            }
            //获得总页数
            $total_page = ceil($count/$page_size);
            //将总页数添加到数组中并返回
            $subject['total_page'] = $total_page;
            $this->apiReturn(200,'查询成功',$result,$count);
        }
    }
    /**
     * @title 新增考试
     * @author 开发者
     * @url /admin/exam/addExam
     * @method POST/GET
     * @description  新增考试 可选择考试类型 1联考2校考
     * @param name:title require:1 default:null type:varchar desc:考试标题
     * @param name:intro require:1 default:null type:text desc:考试说明
     * @param name:review require:1 default:null type:varchar desc:阅卷说明
     * @param name:exam_time require:1 default:null type:text desc:考试时间
     * @param name:tab require:1 default:null type:int desc:考试类型1联考2校考
     * @param name:region require:0 default:null type:varchar desc:地区，联考需设置
     * @param name:school require:0 default:null type:varchar desc:学校
     * @param name:color_content require:1 default:null type:varchar desc:色彩内容
     * @param name:color_img require:0 default:null type:varchar desc:色彩图片地址，可不设置
     * @param name:color_price require:1 default:null type:decimal desc:色彩价格
     * @param name:sketch_content require:1 default:null type:varchar desc:素描内容
     * @param name:sketch_img require:0 default:null type:varchar desc:素描图片地址，可不设置
     * @param name:sketch_price require:1 default:null type:decimal desc:素描价格
     * @param name:draw_content require:1 default:null type:varchar desc:速写内容
     * @param name:draw_img require:0 default:null type:varchar desc:速写图片地址，可不设置
     * @param name:draw_price require:1 default:null type:decimal desc:速写价格
     */
    public function addExam(){
        $data =I('title|intro|review|exam_time|tab|region|school');
        (new ExamValidate())->goCheck();
        //根据标题查询考试信息
        $res = ExamModel::getByTitle($data['title']);
        if($res){
           $this->apiReturn(303,'考试题目不能重复，请重新输入！');
        }
        $result = ExamModel::create($data);
        if(empty($result)){
            $this->apiReturn(303,'考试信息添加失败！');
        }else{
            //获取考试id
            $exam_id = $result['id'];
            $color_data =[
                'name'=>'色彩',
                'content'=>input('color_content'),
                'price' => input('color_price'),
                'img' => input('color_img'),
                'exam_id' => $exam_id,
            ];
            $sketch_data =[
                'name'=>'素描',
                'content'=>input('sketch_content'),
                'price' => input('sketch_price'),
                'img' => input('sketch_img'),
                'exam_id' => $exam_id,
            ];
            $draw_data =[
                'name'=>'色彩',
                'content'=>input('draw_content'),
                'price' => input('draw_price'),
                'img' => input('draw_img'),
                'exam_id' => $exam_id,
            ];
            (new AddSubjects())->goCheck($color_data);
            (new AddSubjects())->goCheck($sketch_data);
            (new AddSubjects())->goCheck($draw_data);
            $subjects = array($color_data,$sketch_data,$draw_data);
            $sub = new SubjectsModel();
            $res = $sub -> saveAll($subjects);
            if($res->isEmpty()){
                $this->apiReturn(303,'考试内容添加失败！');
            }else{
                $this->apiReturn(200,'添加成功！');
            }
        }
    }
    /**
     * @title 获取考试详情
     *@author 开发者
     * @url /admin/exam/getInfoById
     * @method POST/GET
     * @description  根据考试id获取详情 测试id为1
     * @param name:id require:1 default:null type:int desc:考试id
     * @return  id:考试id
     * @return  title:考试标题
     * @return review:阅卷说明
     * @return intro:考试说明
     * @return exam_time:考试时间
     * @return region:地区
     * @return school:学校
     * @return tab:1联考2校考
     * @return create_time: 创建时间
     * @return update_time:更新时间
     * @return subjects:科目详情@
     * @subjects subject_id:科目id name:科目名称 price:科目价格 img:科目考试图 content:科目内容
     */
    public function getInfoById(){
        $id = input('id');
        (new IDMustBePositiveInt())->goCheck();
        $result = ExamModel::getInfoById($id);
        if(empty($result)){
            $this->apiReturn(303,'未查询到相关信息！');
        }else{
            $this->apiReturn(200,'查询成功！',$result);
        }
    }
    /**
     * @title 编辑考试
     * @author 开发者
     * @url /admin/exam/editExam
     * @method POST/GET
     * @description  修改考试内容
     * @param name:id require:1 default:null type:int desc:考试id
     * @param name:title require:1 default:null type:varchar desc:考试标题
     * @param name:intro require:1 default:null type:text desc:考试说明
     * @param name:review require:1 default:null type:varchar desc:阅卷说明
     * @param name:exam_time require:1 default:null type:text desc:考试时间
     * @param name:tab require:1 default:null type:int desc:考试类型1联考2校考
     * @param name:region require:0 default:null type:varchar desc:地区，联考需设置
     * @param name:school require:0 default:null type:varchar desc:学校
     * @param name:color_id require:1 default:null type:int desc:色彩科目id
     * @param name:color_content require:1 default:null type:varchar desc:色彩内容
     * @param name:color_img require:0 default:null type:varchar desc:色彩图片地址，可不设置
     * @param name:color_price require:1 default:null type:decimal desc:色彩价格
     * @param name:sketch_id require:1 default:null type:int desc:素描id
     * @param name:sketch_content require:1 default:null type:varchar desc:素描内容
     * @param name:sketch_img require:0 default:null type:varchar desc:素描图片地址，可不设置
     * @param name:sketch_price require:1 default:null type:decimal desc:素描价格
     * @param name:draw_id require:1 default:null type:int desc:速写科目id
     * @param name:draw_content require:1 default:null type:varchar desc:速写内容
     * @param name:draw_img require:0 default:null type:varchar desc:速写图片地址，可不设置
     * @param name:draw_price require:1 default:null type:decimal desc:速写价格
     */
    public function editExam(){
        $exam_id = input('id');
        $data =I('id|title|intro|review|exam_time|tab|region|school');
        (new IDMustBePositiveInt())->goCheck();
        (new ExamValidate())->goCheck();
        $result = ExamModel::update($data);

        if(empty($result)){
            $this->apiReturn(303,'考试信息修改失败！');
        }else{
            $color_data =[
                'id' => input('color_id'),
                'name'=>'色彩',
                'content'=>input('color_content'),
                'price' => input('color_price'),
                'img' => input('color_img'),
                'exam_id' => $exam_id,
            ];
            $sketch_data =[
                'id' => input('sketch_id'),
                'name'=>'素描',
                'content'=>input('sketch_content'),
                'price' => input('sketch_price'),
                'img' => input('sketch_img'),
                'exam_id' => $exam_id,
            ];
            $draw_data =[
                'id' => input('draw_id'),
                'name'=>'色彩',
                'content'=>input('draw_content'),
                'price' => input('draw_price'),
                'img' => input('draw_img'),
                'exam_id' => $exam_id,
            ];
            (new UpdateSubjects())->goCheck($color_data);
            (new UpdateSubjects())->goCheck($sketch_data);
            (new UpdateSubjects())->goCheck($draw_data);
            $subjects = array($color_data,$sketch_data,$draw_data);
            $sub = new SubjectsModel();
            $res = $sub -> saveAll($subjects);
            if($res->isEmpty()){
                $this->apiReturn(303,'考试内容修改失败！');
            }else{
                $this->apiReturn(200,'修改成功！');
            }
        }
    }
    /**
     * @title 删除考试(假删除，即改变其状态参数,包括其下科目，用户分数等)
     * @author 开发者
     * @url /admin/exam/delExam
     * @method POST/GET
     * @description  删除考试，将status由1变为2
     * @param name:id require:1 default:null type:int desc:考试id
     */
    public function delExam(){
        $id = input('id');
        /*if (!$id) $this->apiReturn(303, '请选择需要删除的考试');
        $subject = ExamModel::with(['subjects'=>function($query){
            $query->where('status',1);
        }])->select($id);
        if(empty($subject['subjects'])){
            $result = ExamModel::where('id','in',$id)->update(['status'=>2]);
            if($result){
                $this->apiReturn(200,'删除成功！');
            }else{
                $this->apiReturn(303,'删除失败！');
            }
        }else{
            $this->apiReturn(303,'请先删除当前考试下的科目！');
        }*/
        if (!$id) $this->apiReturn(303, '请选择需要删除的考试');
        //将字符串转换为数组
        $ids = explode(',',$id);
        foreach ($ids as $v){
            //关联更新
            $result = ExamModel::get($v);
            $result -> update(['status'=>2],['id'=>$v]);
            $result -> subjects()->update(['status'=>2],['exam_id'=>$id]);
            $result -> totalGrade()->update(['status'=>2],['exam_id'=>$id]);
            $result ->grade()->update(['status'=>2],['exam_id'=>$id]);
        }
        halt($result);
        if($result){
            $this->apiReturn(200,'恢复成功！');
        }else{
            $this->apiReturn(303,'恢复失败！');
        }
    }
    /**
     * @title 恢复考试(恢复假删除，即改变其状态参数,相关的科目也同时恢复假删除)
     * @author 开发者
     * @url /admin/exam/restoreExam
     * @method POST/GET
     * @description  恢复假删除，将status由2变为1
     * @param name:id require:1 default:null type:int desc:考试id
     */
    public function restoreExam(){
        $id = input('id');
        if (!$id) $this->apiReturn(303, '请选择需要恢复的考试');
        //将字符串转换为数组
        $ids = explode(',',$id);
        foreach ($ids as $v){
            //关联更新
            $result = ExamModel::get($v);
            $result -> update(['status'=>1],['id'=>$v]);
            $result -> subjects()->update(['status'=>1],['exam_id'=>$id]);
            $result -> totalGrade()->update(['status'=>1],['exam_id'=>$id]);
            $result ->grade()->update(['status'=>1],['exam_id'=>$id]);
        }
        if($result){
            $this->apiReturn(200,'恢复成功！');
        }else{
            $this->apiReturn(303,'恢复失败！');
        }
    }
    /**
     * @title 删除考试(真删除)
     * @author 开发者
     * @url /admin/exam/delExamReal
     * @method POST/GET
     * @description  删除考试数据
     * @param name:id require:1 default:null type:int desc:考试id
     */
    public function delExamReal(){
        $id = input('id');
        if (!$id) $this->apiReturn(303, '请选择需要删除的考试');
        //将字符串转换为数组
        $ids = explode(',',$id);
        foreach ($ids as $v){
            //删除考试相关信息
            TotalGrade::where('exam_id','in',$v)->delete(true);
            $result = ExamModel::get($v,['subjects','grade']);
            $result->together(['subjects','grade'])->delete(true);
        }
        if($result){
            $this->apiReturn(200,'删除成功！');
        }else{
            $this->apiReturn(303,'删除失败！');
        }
    }
    /**
     * @title 根据关键字查询考试信息
     * @author 开发者
     * @url /admin/exam/getExam
     * @method POST/GET
     * @description 根据关键字查询考试
     * @param name:key require:1 default:null type:varchar desc:关键字，可以是标题关键字或地区关键字
     *  @return  id:考试id
     * @return  title:考试标题
     * @return intro:考试说明
     * @return exam_time:考试时间
     * @return region:地区
     * @return school:学校
     * @return tab:1联考 2 校考
     * @return create_time: 创建时间
     * @return update_time:更新时间
     */
    public function getExam(){
        $key = input('key');
        if(!$key)$this->apiReturn(303,'查询关键字不能为空！');
        $result = ExamModel::where('region|title','like',"%{$key}%")->select();
        if($result->isEmpty()){
            $this->apiReturn(303,'未查询到相关信息！');
        }else{
            $this->apiReturn(200,'查询成功',$result);
        }
    }
}